//
//  CTTabBarController.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/29.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTTabBarController.h"

#import "CTHomePageViewController.h"
#import "CTDiscoveryViewController.h"
#import "CTMessageViewController.h"
#import "CTUserViewController.h"
#import "CTLoginViewController.h"

#import "CTPickImageViewController.h"

//config
#import "CTHeader.h"

//view
#import "CTTabBarView.h"

//logic
#import "CTLogic.h"

//function
#import "CTDebugManager.h"
#import "CTUser.h"
#import "CTLogin.h"
#import "CTDeviceFunction.h"
#import "CTAppUpdateItem.h"
#import "CTAppUpdate.h"
#import "CTAppInfo.h"
#import "CTAppLanguage.h"

//tool
#import <objc/runtime.h>
#import "MobClick.h"
#import "CTLoginViewController.h"
#import "CTPickImageViewController.h"

@interface CTTabBarController ()<CTTabBarViewDelegate,UIAlertViewDelegate>
{
    
    CTTabBarView * tabbarView;
    
    CTHomePageViewController * homePageVC;
    CTDiscoveryViewController * discoveryVC;
    CTMessageViewController * messageVC;
    CTUserViewController * userVC;
    
    CTLogic * logic;
}
@end

@implementation CTTabBarController

- (void)dealloc
{
    [tabbarView removeFromSuperview];
    tabbarView = nil;
    
    homePageVC = nil;
    discoveryVC = nil;
    messageVC = nil;
    userVC = nil;
    
    logic = nil;
    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTTabBarController Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tabBar.hidden = YES;
        
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //统计
    [MobClick beginLogPageView:@"CTTabBarController"];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //统计
    [MobClick endLogPageView:@"CTTabBarController"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    NSMutableDictionary *textAttrs=[NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName]= CT_HEADER_ORANGE_COLOR;
    
    
    homePageVC = [[CTHomePageViewController alloc] init];
    homePageVC.tabBarItem.title = [CTAppLanguage localizedStringForKey:@"CTTabBarViewController_subVCOne_title" withValue:nil withTable:@"Language"];
    [homePageVC.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateHighlighted];
    [homePageVC.tabBarItem setFinishedSelectedImage:[[UIImage imageNamed:@"tab_bt_home_click"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] withFinishedUnselectedImage:[[UIImage imageNamed:@"tab_bt_home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

    
    discoveryVC = [[CTDiscoveryViewController alloc] init];
    discoveryVC.tabBarItem.title = [CTAppLanguage localizedStringForKey:@"CTTabBarViewController_subVCTwo_title" withValue:nil withTable:@"Language"];
    [discoveryVC.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateHighlighted];
    [discoveryVC.tabBarItem setFinishedSelectedImage:[[UIImage imageNamed:@"tab_bt_faxian_click"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] withFinishedUnselectedImage:[[UIImage imageNamed:@"tab_bt_faxian"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    
    messageVC = [[CTMessageViewController alloc] init];
    messageVC.tabBarItem.title = [CTAppLanguage localizedStringForKey:@"CTTabBarViewController_subVCThree_title" withValue:nil withTable:@"Language"];
    [messageVC.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateHighlighted];
    [messageVC.tabBarItem setFinishedSelectedImage:[[UIImage imageNamed:@"tab_bt_message_click"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] withFinishedUnselectedImage:[[UIImage imageNamed:@"tab_bt_message"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    
    userVC = [[CTUserViewController alloc] init];
    userVC.pushType = CTUserViewControllerPushFromTypeDefault;
    userVC.userItem = [CTUser userInfo];
    userVC.tabBarItem.title = [CTAppLanguage localizedStringForKey:@"CTTabBarViewController_subVCFour_title" withValue:nil withTable:@"Language"];
    [userVC.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateHighlighted];
    [userVC.tabBarItem setFinishedSelectedImage:[[UIImage imageNamed:@"tab_bt_profile_click"] imageWithRenderingMode:UIMinimumKeepAliveTimeout] withFinishedUnselectedImage:[[UIImage imageNamed:@"tab_bt_profile"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    
    UINavigationController * homePageNav = [[UINavigationController alloc] initWithRootViewController:homePageVC];
    homePageNav.navigationBarHidden = YES;
    UINavigationController * discoveryNav = [[UINavigationController alloc] initWithRootViewController:discoveryVC];
    discoveryNav.navigationBarHidden = YES;
    UINavigationController * messageNav = [[UINavigationController alloc] initWithRootViewController:messageVC];
    messageNav.navigationBarHidden = YES;
    UINavigationController * userNav = [[UINavigationController alloc] initWithRootViewController:userVC];
    userNav.navigationBarHidden = YES;
    
    
    NSArray * vcArray = [NSArray arrayWithObjects:homePageNav,discoveryNav,messageNav,userNav,nil];
    self.viewControllers = vcArray;
    
    
    
    
    tabbarView = [[CTTabBarView alloc] init];
    tabbarView.delegate = self;
    [self.view addSubview:tabbarView];
    
    
    logic = [[CTLogic alloc] init];
    
    //监测版本更新
    [self checkNewVersion];
    
    
    //审核开关
    [self switchAction];
}


#pragma mark - tabbar view delegate -

-(void)selectAction:(CTTabBarView *)view withType:(CTTabBarViewType)type
{
    switch (type) {
        case CTTabBarViewTypeCamera:
            [self presentPickVC];
            break;
        case CTTabBarViewTypeHome:
            self.selectedIndex = 0;
            break;
        case CTTabBarViewTypeDiscovery:
            self.selectedIndex = 1;
            break;
        case CTTabBarViewTypeMessage:
            self.selectedIndex = 2;
            break;
        case CTTabBarViewTypeUserProfile:
            self.selectedIndex = 3;
            break;
        default:
            break;
    }
}

-(void)notiCount
{
    [tabbarView notiCount];
}

#pragma mark - delegate -
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    return YES;
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    
}

- (void)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray *)viewControllers
{
    
}
- (void)tabBarController:(UITabBarController *)tabBarController willEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
    
}
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
    
}



#pragma mark - action -

-(void)presentPickVC
{
    if ([CTLogin isUserLoginState] == YES) {
        //已登录
        CTPickImageViewController * pickImageVC = [[CTPickImageViewController alloc] init];
        UINavigationController * pickImageNav = [[UINavigationController alloc] initWithRootViewController:pickImageVC];
        pickImageNav.navigationBarHidden = YES;
        [self presentViewController:pickImageNav animated:YES completion:^{
            
        }];
    }else{
        //未登录
        CTLoginViewController * loginVC = [[CTLoginViewController alloc] init];
        UINavigationController * loginNav = [[UINavigationController alloc] initWithRootViewController:loginVC];
        loginNav.navigationBarHidden = YES;
        
        [self presentViewController:loginNav animated:YES completion:^{
            
        }];
    }
}


-(void)showTabbarWithAnimate:(BOOL)animate
{
    if (animate == YES) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = tabbarView.frame;
            frame.origin.y = CT_HEADER_SCREEN_HEIGHT - 50;
            tabbarView.frame = frame;
        }];
    }else{
        tabbarView.hidden = NO;
    }
}
-(void)hideTabbarWithAnimate:(BOOL)animate
{
    if (animate == YES) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = tabbarView.frame;
            frame.origin.y = CT_HEADER_SCREEN_HEIGHT + 50;
            tabbarView.frame = frame;
        }];
    }else{
        tabbarView.hidden = YES;
    }
}

-(void)selectTabbarIndex:(NSInteger)index
{
    self.selectedIndex = index;
    [tabbarView selectIndex:index];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    [CTDebugManager showDebugLogInfo:@"CTTabBarController内存警告!!!"];
}



#pragma mark - 审核开关 -
-(void)switchAction
{
    if ([CTAppInfo isAppOnline] == NO) {
        [self sendSwitchRequest];
    }
}

-(void)sendSwitchRequest
{
    [logic auditStatusRequest:[CTAppInfo appVersion] successCompletionHandler:^{
        
    } failedHandler:^{
       
    }];
}


#pragma mark - 新版本更新 -
-(void)checkNewVersion
{
    __block NSString * url;
    __block BOOL isForce;
    
    
    NSString * alertTitle = [CTAppLanguage localizedStringForKey:@"alert_title" withValue:nil withTable:@"Language"];
    NSString * alertConfirmBtn = [CTAppLanguage localizedStringForKey:@"alert_confirmBtn" withValue:nil withTable:@"Language"];
    NSString * alertCancelBtn = [CTAppLanguage localizedStringForKey:@"alert_cancleBtn" withValue:nil withTable:@"Language"];
    
    [CTAppUpdate checkAppUpdateWithForceUpdateHandler:^(CTAppUpdateItem *versionInfoModel) {
        [CTDebugManager showDebugLogInfo:@"强制更新"];
        
        url = versionInfoModel.url;
        isForce = YES;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView * alertView= [[UIAlertView alloc] initWithTitle:alertTitle message:versionInfoModel.describe delegate:self cancelButtonTitle:nil otherButtonTitles:alertConfirmBtn, nil];
            [alertView show];
        });
        
    } CommonUpdateHandler:^(CTAppUpdateItem *versionInfoModel) {
        [CTDebugManager showDebugLogInfo:@"普通更新"];
        
        url = versionInfoModel.url;
        isForce = NO;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView * alertView= [[UIAlertView alloc] initWithTitle:alertTitle message:versionInfoModel.describe delegate:self cancelButtonTitle:alertCancelBtn otherButtonTitles:alertConfirmBtn, nil];
            [alertView show];
        });
        
    } NoneUpdateHandler:^{
        [CTDebugManager showDebugLogInfo:@"没有版本更新，什么也不做"];
       
        
    }];
    
    
    void (^updateComposeBlock)(UIAlertView *,NSInteger) = ^(UIAlertView * alertView,NSInteger index){
        if (isForce == YES) {
            if (index == 0)[CTDeviceFunction jumpToAppStore:url];
        }else{
            if (index == 1)[CTDeviceFunction jumpToAppStore:url];
        }
    };
    
    void (^updateFinishBlock)() = ^(){
        if (isForce == YES)[self checkNewVersion];
    };
    
    objc_setAssociatedObject(self, &updateComposeKey,updateComposeBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &updateFinishKey,updateFinishBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

//delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    void (^blcok)(UIAlertView *,NSInteger) = objc_getAssociatedObject(self, &updateComposeKey);
    blcok(alertView,buttonIndex);
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    void (^blcok)() = objc_getAssociatedObject(self, &updateFinishKey);
    objc_removeAssociatedObjects(self);
    blcok();
}


@end
